﻿#include "pch.h"

extern WoHTTPHanderErrorFunc g_handerError = nullptr;
//#include "oatpp/web/server/HttpRouter.hpp"
typedef std::shared_ptr< oatpp::web::protocol::http::outgoing::Response>
(*HttpRequestHandlerErrorFunc)(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>&,
	const std::shared_ptr<oatpp::web::protocol::http::HttpError>&);

void WEBOAT_API WoHTTPSetErrorHander(WoHttpRouterPtr&r, void* func) {
	r->SetHttpRequestHandlerErrorCallback(GlobalHandlerError);
	
}

std::shared_ptr<oatpp::web::protocol::http::outgoing::Response>
GlobalHandlerError(const std::shared_ptr<oatpp::web::protocol::http::incoming::Request>&req,
	const std::shared_ptr<oatpp::web::protocol::http::HttpError>&err) {
	//错误
	auto end_time = std::chrono::high_resolution_clock::now();
	auto elapsed_time = std::chrono::duration_cast<std::chrono::nanoseconds>(end_time - req->m_start_time).count();
	if (err->getInfo().status.code==404) {
		g_logger->warn("| [{:^5}] | [{:^9}] | {:>10} | {}", err->getInfo().status.code,
			std::string((char*)req->getStartingLine().method.getData(), req->getStartingLine().method.getSize()), 
			WoHaperTimeconversion(elapsed_time),
			std::string((char*)req->getStartingLine().path.getData(), req->getStartingLine().path.getSize()));
	}
	else {
		g_logger->error("| [{:^5}] | [{:^9}] | {:>10} | {}", err->getInfo().status.code, 
			std::string((char*)req->getStartingLine().method.getData(), req->getStartingLine().method.getSize()),
			WoHaperTimeconversion(elapsed_time),
			std::string((char*)req->getStartingLine().path.getData(), req->getStartingLine().path.getSize()));
	}
	auto resp = oatpp::web::protocol::http::outgoing::ResponseFactory::createResponse(
		err->getInfo().status, err->getMessage()
	);
	resp->putHeader("Content-Type", "text/html; charset=utf-8");
	if (g_handerError==nullptr) {
		return resp;
	}
	WoHTTPContext ctx(req, resp);
	g_handerError(ctx);
	return ctx;
}

void WEBOAT_API WoHTTPSetGlobalHandlerError(WoHTTPHanderErrorFunc func) {
	g_handerError = func;
}